package main

import (
	"encoding/json"
	"fmt"
	"net/http"

	consulapi "github.com/hashicorp/consul/api"
)

const (
	port = 3003
)

func Register() {
	config := consulapi.DefaultConfig()
	config.Token = "7179b358-cdc1-4108-9ca0-5c063dd1b1c1"
	config.Address = "29.3.91.232:8500"
	client, err := consulapi.NewClient(config)
	if err != nil {
		panic(err)
	}

	register := &consulapi.AgentServiceRegistration{
		Name:    "fps-mars-90835-fps-mars",
		Tags:    []string{"appId=90835", "management.base-path=/actuator/halo/status", "subenv=fat", "subenv=fat001", "fat", "zone=testcore"},
		ID:      fmt.Sprintf("fps-mars-90835-fps-mars-%d", port),
		Port:    3003,
		Address: "29.3.91.232",

		Check: &consulapi.AgentServiceCheck{
			HTTP:                           "http://29.3.91.232:3003/actuator/halo/status",
			Timeout:                        "5s",
			Interval:                       "5s",
			DeregisterCriticalServiceAfter: "30s",
		},
	}

	if err = client.Agent().ServiceRegister(register); err != nil {
		panic(err)
	}
}

func agenDiscovery() {
	config := consulapi.DefaultConfig()
	config.Token = "7179b358-cdc1-4108-9ca0-5c063dd1b1c1"
	config.Address = "29.3.201.104:8080" // server
	// config.Address = "29.3.91.232:8500" // agent
	client, err := consulapi.NewClient(config)
	if err != nil {
		panic(err)
	}

	// service, err := client.Agent().Services()
	// service, data, err := client.Catalog().Services(nil)
	service, data, err := client.Health().Service("fps-mars-90835-fps-mars", "appId=90835", false, nil)

	if err != nil {
		panic(err)
	}

	if datas, err := json.Marshal(data); err != nil {
		panic(err)
	} else {
		fmt.Println(string(datas))
	}

	if services, err := json.Marshal(service); err != nil {
		panic(err)
	} else {
		fmt.Println(string(services))
	}
}

func main() {

	Register()

	if err := http.ListenAndServe(":3003", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Println("---------------", r.RequestURI)
		agenDiscovery()
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("this is health page"))
	})); err != nil {
		panic(err)
	}
}
